package ink.xiaobaibai.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import ink.xiaobaibai.security.ClientInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @description: 安全配置类
 * @author: 小白白
 * @create: 2021-05-19
 **/

@Configuration
public class SecurityConfig extends WebMvcConfigurationSupport {

    @Autowired
    private ApplicationContext applicationContext;

    private ClientInterceptor clientInterceptor = new ClientInterceptor();

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.clientInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/error", "/user/login", "/wx-pay/callback", "/local/**", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }

    /**
     * 如果项目使用了swagger2接口测试工具，那么需要重写这个方法，不然接口测试url访问不了，被拦截了
     *
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源无法访问
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder json = Jackson2ObjectMapperBuilder.json();
        json.applicationContext(this.applicationContext);
        json.serializationInclusion(JsonInclude.Include.NON_NULL);
        converters.removeIf(f -> f.getClass() == MappingJackson2HttpMessageConverter.class);
        converters.add(new MappingJackson2HttpMessageConverter(json.build()));
    }

}
